#!/bin/bash

# ERP Mock Server SystemD 服务配置修复脚本
echo "🔧 修复 ERP Mock Server SystemD 服务配置..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置变量
APP_DIR="/opt/erp-mock"
SERVICE_NAME="erp-mock"
USER_NAME=$(whoami)

echo -e "${BLUE}当前用户: $USER_NAME${NC}"
echo -e "${BLUE}应用目录: $APP_DIR${NC}"

# 1. 检查当前服务状态
echo -e "${BLUE}🔍 检查现有服务状态...${NC}"
if systemctl list-unit-files | grep -q "erp-mock"; then
    echo -e "${YELLOW}发现现有服务，正在清理...${NC}"
    sudo systemctl stop erp-mock 2>/dev/null || true
    sudo systemctl disable erp-mock 2>/dev/null || true
fi

# 2. 查找当前运行的ERP Mock进程
echo -e "${BLUE}🔍 检查运行中的ERP Mock进程...${NC}"
PIDS=$(ps aux | grep "[p]ython.*main.py" | awk '{print $2}')
if [ ! -z "$PIDS" ]; then
    echo -e "${YELLOW}发现运行中的进程: $PIDS${NC}"
    echo -e "${YELLOW}正在停止现有进程...${NC}"
    echo "$PIDS" | xargs kill -9 2>/dev/null || true
    sleep 2
fi

# 3. 创建systemd服务文件
echo -e "${BLUE}📝 创建systemd服务文件...${NC}"
sudo tee /etc/systemd/system/erp-mock.service > /dev/null <<EOF
[Unit]
Description=ERP Mock Server
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$APP_DIR
Environment="FLASK_ENV=production"
Environment="PYTHONPATH=$APP_DIR"
ExecStart=$APP_DIR/venv/bin/python main.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

echo -e "${GREEN}✅ 服务文件已创建${NC}"

# 4. 验证Python虚拟环境
echo -e "${BLUE}🔍 验证Python虚拟环境...${NC}"
if [ ! -f "$APP_DIR/venv/bin/python" ]; then
    echo -e "${RED}❌ 虚拟环境不存在，正在创建...${NC}"
    cd $APP_DIR
    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
    echo -e "${GREEN}✅ 虚拟环境创建完成${NC}"
else
    echo -e "${GREEN}✅ 虚拟环境已存在${NC}"
fi

# 5. 设置正确的权限
echo -e "${BLUE}🔐 设置文件权限...${NC}"
sudo chown -R $USER_NAME:$USER_NAME $APP_DIR
chmod +x $APP_DIR/main.py

# 6. 重新加载systemd配置
echo -e "${BLUE}🔄 重新加载systemd配置...${NC}"
sudo systemctl daemon-reload

# 7. 启用并启动服务
echo -e "${BLUE}🚀 启用并启动服务...${NC}"
sudo systemctl enable erp-mock
sudo systemctl start erp-mock

# 8. 等待服务启动
echo -e "${BLUE}⏳ 等待服务启动...${NC}"
sleep 5

# 9. 检查服务状态
echo -e "${BLUE}🔍 检查服务状态...${NC}"
if systemctl is-active --quiet erp-mock; then
    echo -e "${GREEN}✅ 服务启动成功！${NC}"

    # 显示服务状态
    echo -e "${BLUE}📊 服务状态:${NC}"
    sudo systemctl status erp-mock --no-pager

    echo ""
    echo -e "${BLUE}🌐 测试健康检查:${NC}"
    sleep 2
    if curl -s http://localhost:3003/health > /dev/null; then
        echo -e "${GREEN}✅ 健康检查通过${NC}"
    else
        echo -e "${YELLOW}⚠️ 健康检查失败，但服务可能仍在启动中${NC}"
    fi

else
    echo -e "${RED}❌ 服务启动失败${NC}"
    echo -e "${YELLOW}查看错误日志:${NC}"
    sudo journalctl -u erp-mock --no-pager -n 20
    exit 1
fi

# 10. 显示管理命令
echo ""
echo "=================================================="
echo -e "${GREEN}🎉 SystemD服务配置完成！${NC}"
echo "=================================================="
echo -e "${BLUE}常用管理命令:${NC}"
echo "• 查看状态: sudo systemctl status erp-mock"
echo "• 启动服务: sudo systemctl start erp-mock"
echo "• 停止服务: sudo systemctl stop erp-mock"
echo "• 重启服务: sudo systemctl restart erp-mock"
echo "• 查看日志: sudo journalctl -u erp-mock -f"
echo "• 禁用服务: sudo systemctl disable erp-mock"
echo ""
echo -e "${BLUE}🌐 访问地址:${NC}"
echo "• 健康检查: http://your-server-ip:3003/health"
echo "• 管理界面: http://your-server-ip:3003/admin"
echo ""
echo -e "${YELLOW}💡 提示: 现在可以使用 sudo systemctl stop erp-mock 来停止服务了${NC}"